package com.ksd.quartz.task;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.enums.SourceTypeEnum;
import com.ksd.common.enums.SynchContentStatusEnum;
import com.ksd.common.excel.ExcelReader;
import com.ksd.common.excel.ExcelTool;
import com.ksd.common.excel.MovieExcel;
import com.ksd.common.excel.MusicExcel;
import com.ksd.common.utils.DateUtils;
import com.ksd.common.utils.StringUtils;
import com.ksd.quartz.http.DRMHttpClient;
import com.ksd.quartz.http.NIOFileDownloader;
import com.ksd.quartz.service.MovieExcelService;
import com.ksd.quartz.service.MusicExcelService;
import com.ksd.quartz.task.beans.SynchDataRequest;
import com.ksd.quartz.task.beans.SynchDataResponse;
import com.ksd.quartz.util.TaskConstans;
import com.ksd.quartz.util.UnzipUtility;
import com.ksd.system.domain.*;
import com.ksd.system.service.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 将从远程下下来的压缩包进行同步下载,解压缩,入库
 */
@Component("synchContentZipTask")
public class SynchContentZipTask {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(SynchContentZipTask.class);

    @Autowired
    private ISysSynchDataService sysSynchDataService;
    @Autowired
    private ISysBatchService sysBatchService;
    @Autowired
    private MovieExcelService movieExcelService;
    @Autowired
    private MusicExcelService musicExcelService;
    @Autowired
    private ISysMovieService sysMovieService;
    @Autowired
    private ISysMusicDataService sysMusicDataService;
    @Autowired
    private ISysOperLogService sysOperLogService;

    private Map<String, Integer> uploadProgressMap = new HashMap<>();
    private Map<String, Integer> uploadProgressTotalMap = new HashMap<>();


    public void synchMovieAndMusic() throws IOException {
        logger.info("开始查询数据库是否有待同步入库的压缩包内容(电影/音乐)的数据,如果有的话,开始解析指定目录下的内容文件");
        //先通过接口将压缩包数据下载到本地服务上-->进入数据导入表记录中
        //解压
        //读取配置文件,分辨是电影内容还是音乐内容
        //入库--->批次记录
        SysSynchData sysSynchData = new SysSynchData();
        sysSynchData.setStatus(SynchContentStatusEnum.wait.getCode());
        List<SysSynchData> synchDataList = sysSynchDataService.selectSysSynchDataList(sysSynchData);
        logger.info("等待解压同步的内容数据个数:"+synchDataList.size());
        sysOperLogService.insertOperlogApiSuccess("等待解压同步的内容数据个数:"+synchDataList.size());
        for (SysSynchData synchData : synchDataList) {
            logger.info("解析上传目录的文件的所有文件,进行数据录入,可能存在电影,音乐");

            String mapperFilePath = synchData.getUnzipPath();
            logger.info("检测待同步的内容数据文件夹目录mapperFilePath:"+mapperFilePath);
            sysOperLogService.insertOperlogApiSuccess("检测待同步的内容数据文件夹目录mapperFilePath:"+mapperFilePath);
            synchData.setStatus(SynchContentStatusEnum.synch.getCode());//正在导入
            sysSynchDataService.updateSysSynchData(synchData);

            synchData = sysSynchDataService.selectSysSynchDataById(synchData.getId());
            //读取mapperFilePath目录下的文件或者文件夹,找出对应的电影或者音乐,入库
            String taskId = "";
            SysBatch result = new SysBatch();
            do {
                taskId = UUID.randomUUID().toString();
                result = sysBatchService.selectSysBatchByTaskId(taskId);
            }while (StringUtils.isNotNull(result));
            uploadProgressMap.put(taskId, 0);
            uploadProgressTotalMap.put(taskId, 0);
            importSynchData(mapperFilePath,synchData,taskId);
        }
        logger.info("将内容压缩包数据入库结束=========================================end");
    }

    public void importSynchData(String synchUnzipDataPath,SysSynchData synchData,String taskId) throws IOException {
        //获取synchUnzipDataPath 目录下符合条件.excel文件,默认导入所有

        logger.info("从内容同步系统同步接口解压缩同步根目录:"+synchUnzipDataPath);
        sysOperLogService.insertOperlogApiSuccess("从内容同步系统同步接口解压缩同步根目录:"+synchUnzipDataPath);

        LinkedHashSet<String> movieExcelFiles = ExcelTool.findMovieExcelFileAll(synchUnzipDataPath);
        LinkedHashSet<String> musicExcelFiles = ExcelTool.findMusicExcelFileAll(synchUnzipDataPath);

        logger.info("内容同步,检测到的待同步电影Excel文件个数:"+movieExcelFiles.size());
        sysOperLogService.insertOperlogApiSuccess("内容同步,检测到的待同步电影Excel文件个数:"+movieExcelFiles.size());
        logger.info("内容同步,检测到的待同步歌曲Excel文件个数:"+musicExcelFiles.size());
        sysOperLogService.insertOperlogApiSuccess("内容同步,检测到的待同步歌曲Excel文件个数:"+musicExcelFiles.size());
        Integer sourceType = SourceTypeEnum.synch.getCode();
        for (String movieExcelFile : movieExcelFiles) {
            logger.info("从内容同步系统同步接口解压缩电影的Excel文件:"+movieExcelFile);
            sysOperLogService.insertOperlogApiSuccess("从内容同步系统同步接口解压缩电影的Excel文件:"+movieExcelFile);
            File excelFile = new File(movieExcelFile);
            List<MovieExcel> movieExcels = ExcelReader.readExcelMovieFile(excelFile);

            if (movieExcels != null && movieExcels.size() > 0) {
                SysBatch sysBatchSql = new SysBatch();
                sysBatchSql.setTaskId(taskId);
                sysBatchSql.setType(SysTvType.movieDefaultId);
                List<SysBatch> sysBatches = sysBatchService.selectSysBatchList(sysBatchSql);
                if (sysBatches.size() == 0) {
                    sysBatchSql.setStartTime(new Date());
                    sysBatchService.insertSysBatch(sysBatchSql);
                }
            }
            String parent = excelFile.getParent();
            movieExcelService.insertReadExcelByRootPath(parent,movieExcels,taskId,sourceType);

            String absolutePath = excelFile.getParentFile().getAbsolutePath();
            String fileName = excelFile.getName();
            String newFilePath = absolutePath + File.separator + "已入库_"+fileName+".bak_"+ DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
            Path newPath = Paths.get(newFilePath);
            Path originalPath = Paths.get(excelFile.getAbsolutePath());
            Files.move(originalPath, newPath);
        }

        for (String musicExcelFile : musicExcelFiles) {
            logger.info("从内容同步系统同步接口解压缩歌曲的Excel文件:"+musicExcelFile);
            sysOperLogService.insertOperlogApiSuccess("从内容同步系统同步接口解压缩歌曲的Excel文件:"+musicExcelFile);
            File excelFile = new File(musicExcelFile);
            List<MusicExcel> musicExcels = ExcelReader.readExcelMusicFile(excelFile);

            if (musicExcels != null && musicExcels.size() > 0) {
                SysBatch sysBatchSql = new SysBatch();
                sysBatchSql.setTaskId(taskId);
                sysBatchSql.setType(SysTvType.songDefaultId);
                List<SysBatch> sysBatches = sysBatchService.selectSysBatchList(sysBatchSql);
                if (sysBatches.size() == 0) {
                    sysBatchSql.setStartTime(new Date());
                    sysBatchService.insertSysBatch(sysBatchSql);
                }
            }
            String parent = excelFile.getParent();
            musicExcelService.insertReadExcelByRootPath(parent,musicExcels,taskId,sourceType);


            String absolutePath = excelFile.getParentFile().getAbsolutePath();
            String fileName = excelFile.getName();
            String newFilePath = absolutePath + File.separator + "已入库_"+fileName+".bak_"+ DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
            Path newPath = Paths.get(newFilePath);
            Path originalPath = Paths.get(excelFile.getAbsolutePath());
            Files.move(originalPath, newPath);
        }


        //更新远程服务器内容同步记录
        updateSynchContentBatch(taskId);

        logger.info("待同步电影Excel文件个数:"+movieExcelFiles.size());
        sysOperLogService.insertOperlogApiSuccess("待同步电影Excel文件个数:"+movieExcelFiles.size());
        logger.info("待同步歌曲Excel文件个数:"+musicExcelFiles.size());
        sysOperLogService.insertOperlogApiSuccess("待同步歌曲Excel文件个数:"+musicExcelFiles.size());
        if (musicExcelFiles.size() == 0 && movieExcelFiles.size() == 0) {
            synchData.setStatus(SynchContentStatusEnum.synch_failed.getCode());
        }else{
            synchData.setStatus(SynchContentStatusEnum.success.getCode());
        }
        sysSynchDataService.updateSysSynchData(synchData);

    }

    public void updateSynchContentBatch(String taskId) throws IOException {
        SysBatch sysBatchTemp = new SysBatch();
        sysBatchTemp.setTaskId(taskId);
        List<SysBatch> sysBatches = sysBatchService.selectSysBatchList(sysBatchTemp);
        logger.info("更新此次内容同步的批次记录:"+sysBatches.size()+"========taskId:"+taskId);
        for (SysBatch sysBatch : sysBatches) {
            String type = sysBatch.getType();
            if (type.equals(SysTvType.movieDefaultId)){
                SysMovie sysMovie = new SysMovie();
                sysMovie.setTaskId(taskId);
                List<SysMovie> movieList = sysMovieService.selectSysMovieList(sysMovie);
                logger.info("电影的批次记录:"+movieList.size());
                if (movieList.size() != 0) {
                    sysBatch.setStatus("0");
                    sysBatch.setNumber(String.valueOf(movieList.size()));
                    sysBatch.setEndTime(new Date());
                    sysBatch.setContentEnd(movieList.get(0).getId().toString());
                    sysBatch.setContentStart(movieList.get(movieList.size() - 1).getId().toString());
                    sysBatch.setRemake("内容同步系统导入");
                    sysOperLogService.insertOperlogApiSuccess("从远程服务器通过接口电影内容同步记录更新");
                    sysBatchService.updateSysBatch(sysBatch);
                }
            }else if(type.equals(SysTvType.songDefaultId)){
                SysMusicData sysMusicData = new SysMusicData();
                sysMusicData.setTaskId(taskId);
                List<SysMusicData> sysMusicDataList = sysMusicDataService.selectSysMusicDataList(sysMusicData);
                logger.info("歌曲的批次记录:"+sysMusicDataList.size());
                if (sysMusicDataList.size() != 0){
                    sysBatch.setStatus("0");
                    sysBatch.setNumber(String.valueOf(sysMusicDataList.size()));
                    sysBatch.setEndTime(new Date());
                    sysBatch.setContentEnd(sysMusicDataList.get(0).getId().toString());
                    sysBatch.setContentStart(sysMusicDataList.get(sysMusicDataList.size() - 1).getId().toString());
                    sysBatch.setRemake("内容同步系统导入");
                    sysOperLogService.insertOperlogApiSuccess("从远程服务器通过接口做歌曲内容同步记录更新");
                    sysBatchService.updateSysBatch(sysBatch);
                }
            }
        }
    }

}
